package com.rockcent.third.controller;

import javax.servlet.http.HttpServletRequest;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.MallProtocolDto;
import com.rockcent.mall.lib.dto.MerchantDto;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantSrv;
import com.rockcent.third.Prop;
import com.rockcent.third.helper.*;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.rockcent.third.Routes;
import com.rockcent.mall.lib.dto.MallDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * Created by HK on 16/12/27.
 * 官网入驻平台管理
 */
@RestController
public class MallController extends BaseController {
    private static Logger log = LoggerFactory.getLogger(MallController.class);

    @Autowired
    private UserHelper userHelper;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private MallCertifyConfigsRepository mallCertifyConfigsRepository;
    @Autowired
    private CertifyConfigRepository certifyConfigRepository;
    @Autowired
    private MallFundRepository mallFundRepository;
    @Autowired
    private Prop prop;
    @Autowired
    private MallHelper mallHelper;
    @Autowired
    private MerchantProductRepository merchantProductRepository;
    @Autowired
    private MallProtocolRepository mallProtocolRepository;
    @Autowired
    private CodeHelper codeHelper;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private MerchantSrv merchantSrv;


    /**
     * @api {post} /mall/settled 平台入驻
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} companyName <code>必传参数</code> 公司名称
     * @apiParam {String} name <code>必传参数</code> 平台名称
     * @apiParam {String} hostName <code>必传参数</code> 域名
     * @apiParam {String} userInfoMobile <code>必传参数</code> 联系人手机
     * @apiParam {String} userInfoEmail <code>必传参数</code> 联系人邮箱
     *
     * @apiSuccess {String=1("成功"), 3("失败"), 10("你已成功开通平台,不能重复开通"), 11("公司名称已经存在"), 12("平台名称已经被使用"), 13("域名已经存在")} code 返回码
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *    "code": "1",
     *    "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_SETTLED, method = RequestMethod.POST)
    public JsonResult mallSettled(@RequestBody MallDto mallDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            UserInfo userInfo = userInfoRepository.findById(userInfoDto.getId());
            Mall mall = mallRepository.findByUserInfoId(userInfoDto.getId());
            if (mall != null) {
                jsonResult.custom("10", "你已成功开通平台,不能重复开通", log);
                return;
            }

            //公司名称校验
            if (StringUtils.isBlank(mallDto.getCompanyName())) {
                jsonResult.remind(Mall.CHECK_COMPANY_NAME_IS_NOT_NULL,log);
                return;
            }
            List<Mall> mallList = mallRepository.findByCompanyName(mallDto.getCompanyName());
            if (mallList.size() > 0) {
                jsonResult.custom("11", "公司名称已经存在", log);
                return;
            }

            //平台名称校验
            if (StringUtils.isBlank(mallDto.getName())) {
                jsonResult.remind(Mall.CHECK_NAME_IS_NOT_NULL,log);
                return;
            }
            mallList = mallRepository.findByName(mallDto.getName());
            if (mallList.size() > 0) {
                jsonResult.custom("12", "平台名称已经被使用", log);
                return;
            }

            //域名校验
            if (StringUtils.isBlank(mallDto.getHostName())) {
                jsonResult.remind(Mall.CHECK_HOSTNAME_IS_NOT_NULL,log);
                return;
            }
            String hostName = mallDto.getHostName().toLowerCase() + prop.mallSettledM;
            mall = mallRepository.findByHostname(hostName);
            if (mall != null) {
                jsonResult.custom("13", "域名已经存在", log);
                return;
            }

//            if (StringUtils.isBlank(mallDto.getUserInfoMobile())) {
//                jsonResult.remind(Mall.CHECK_MOBILE_IS_NOT_NULL);
//                return;
//            }
//            if (StringUtils.isBlank(mallDto.getUserInfoEmail())) {
//                jsonResult.remind(Mall.CHECK_CONTACT_IS_NOT_NULL);
//                return;
//            }

            if (StringUtils.isBlank(userInfo.getRealName())) {
                userInfo.setRealName(mallDto.getUserInfoRealName());
            }
            if (StringUtils.isBlank(userInfo.getMobile())) {
                userInfo.setMobile(mallDto.getUserInfoMobile());
            }
            if (StringUtils.isBlank(userInfo.getEmail())) {
                userInfo.setEmail(mallDto.getUserInfoEmail());
            }
            // 保存用户信息
            userInfoRepository.save(userInfo);

            // 保存平台信息
            mall = new Mall();
            mall.setName(mallDto.getName());
            mall.setHostname(mallDto.getHostName().toLowerCase() + prop.mallSettledM);// xxx.b.rockcent.com
            mall.setMobileHostName(mallDto.getHostName().toLowerCase() + prop.mallSettledC); // xxx.c.rockckent.com
            mall.setCompanyName(mallDto.getCompanyName());
            mall.setUserInfoId(userInfoDto.getId());
            mall.setSalesCode(codeHelper.genMallSaleCode());
            mall = mallRepository.save(mall);

            //添加平台财务设置
            mallHelper.saveMallFinancialSettings(mall.getId());

            //创建一个平台资金账号
            MallFund mallFund = new MallFund();
            mallFund.setMallId(mall.getId());
            mallFund = mallFundRepository.save(mallFund);
            mall.setMallFundId(mallFund.getId());
            mall = mallRepository.save(mall);

            final Mall finalMall = mall;
            //添加默认的实名认证设置
            List<CertifyConfig> certifyConfigList = certifyConfigRepository.findBySelected(true);
            certifyConfigList.forEach(certifyConfig -> {
                mallCertifyConfigsRepository.save(finalMall.getId(), certifyConfig.getCode());
            });

            //创建平台会员
            MallMember mallMember = mallHelper.saveMallMember(mall.getId());
            //创建平台支付标准协议
            mallHelper.saveMallPayStandard(mall.getId(), mallMember.getId());

            //创建平台服务协议
            List<MallProtocol> mallProtocolList =  mallProtocolRepository.findByMallId(0L);
            mallProtocolList.forEach(mallProtocol -> {
                MallProtocol protocol = new MallProtocol();
                protocol.setMallId(finalMall.getId());
                protocol.setProtocolType(mallProtocol.getProtocolType());
                protocol.setContent(mallProtocol.getContent());
                protocol.setTitle(mallProtocol.getTitle());
                mallProtocolRepository.save(protocol);
            });

            //默认添加权限  默认写死权限 角色:平台超级管理员 商户超级管理员 权限:平台超级管理员 商户超级管理员
            mallHelper.saveRolePermission(1L, 1L, finalMall.getId());
            mallHelper.saveRolePermission(2L, 2L, finalMall.getId());
            mallHelper.saveUserRole(1L, finalMall.getId(), userInfoDto.id);
            mallHelper.saveUserRole(2L, finalMall.getId(), userInfoDto.id);

            // 添加平台品类模板
            mallHelper.saveCateTemplates(finalMall.getId());

            //创建一个商家
            mallHelper.saveMerchant(userInfo, mall, mallDto.getCompanyName());


            // 添加平台默认菜单权限
            mallHelper.saveAuthResource(mall, userInfo.getUsername());

        };

        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/settled_list 平台 分页
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {long} id 平台Id
     * @apiSuccess {String} serveRate 服务费率
     * @apiSuccess {String} name 平台名称
     * @apiSuccess {String} qRCodeUrl 二维码
     * @apiSuccess {String} logoSmallPicture 平台logo
     * @apiSuccess {String} industry 行业
     * @apiSuccess {String} hostName 配置的域名地址
     * @apiSuccess {String} customerPlatformDomain 自定义域名
     * @apiSuccess {String} introduce 平台简介
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功",
     *      "data": {
     *          [
     *        {
     *          "id": 1012,
     *          "serveRate": "2.5",
     *          "name": "简约大气OL风打底衫",
     *          "qRCodeUrl": "2334252345234532.jpg",
     *          "logoSmallPicture": "2334252345234532.jpg",
     *          "industry": "卖鱼",
     *          "customerPlatformDomain": "wzz.b.dev.rockcent.com",
     *          "hostName": "wzz.b.dev.rockcent.com",
     *          "introduce": "简约大气OL风打底衫"
     *      },
     *      ......
     *      ]
     * }
     */
    @RequestMapping(value = Routes.MALL_SETTLED_LIST, method = RequestMethod.GET)
    public JsonResult mallList(HttpServletRequest request, MallDto mallDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            PageResult<MallDto> pageResult = mallRepository.findMallList(userInfoDto.getId(), this.getPage(mallDto.getPageNo(), mallDto.getPageSize()));
            pageResult.setUrl(Routes.MALL_SETTLED_LIST);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/settled_detail 平台详情
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam  {long} mallId <code>必传参数</code> 平台Id
     *
     * @apiSuccess {long} id 平台Id
     * @apiSuccess {String} serveRate 服务费率
     * @apiSuccess {String} name 平台名称
     * @apiSuccess {String} qRCodeUrl 二维码
     * @apiSuccess {String} logoSmallPicture 平台logo
     * @apiSuccess {String} industry 行业
     * @apiSuccess {String} introduce 平台介绍
     * @apiSuccess {long} productCount 产品数
     * @apiSuccess {long} merchantCount 商户数
     * @apiSuccess {long} channelCount 渠道数
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功",
     *      "data": {
     *          "id": 1012,
     *          "serveRate": "2.5",
     *          "name": "简约大气OL风打底衫",
     *          "qRCodeUrl": "2334252345234532.jpg",
     *          "logoSmallPicture": "2334252345234532.jpg",
     *          "industry": "卖鱼",
     *          "introduce": "简约大气OL风打底衫",
     *          "productCount": 341,
     *          "merchantCount": 12,
     *          "channelCount": 12
     *      }
     * }
     */
    @RequestMapping(value = Routes.MALL_SETTLED_DETAIL, method = RequestMethod.GET)
    public JsonResult mallInfo(HttpServletRequest request, Long mallId) {
        RestDoing doing = jsonResult -> {
            if (mallId == null) {
                jsonResult.remind(Mall.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MallDto mallDto = mallRepository.findMallInfo(mallId);
            int mallMerchantCount = merchantRepository.countByMallIdAndStatus(mallId, MerchantStatus.VERIFIED);
            int mallProductCount = merchantProductRepository.countByMallIdAndIsDeleteAndStatusInAndMarketIdIsNull(mallId, Whether.NO, Arrays.asList(ProductStatus.AUDIT_FAIL, ProductStatus.WAIT_AUDIT, ProductStatus.DRAFT));
            int mallChannelCount = channelRepository.countByMallIdAndChannelStatusAndIsDelete(mallId, ChannelStatus.USING, Whether.NO);
            mallDto.setProductCount(mallProductCount);
            mallDto.setMerchantCount(mallMerchantCount);
            mallDto.setChannelCount(mallChannelCount);
            jsonResult.data = mallDto;
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /mall/settled_protocols_info 商户服务协议详情
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Long} mallId 平台ID
     * @apiParam {String=MERCHANT_PROTOCOL("商户服务协议")} protocolType <code>必传参数</code> 协议类型
     * @apiParam {String=SELF("自定义"), DEFAULT("配置域名")} type <code>必传参数</code> 协议类型
     *
     * @apiSuccess {Long} id 协议ID
     * @apiSuccess {String} title 协议标题
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} content 协议内容
     * @apiSuccess {Long} versionNo 协议版本号
     * @apiSuccess {String=CUSTOMER_PROTOCOL("C端用户注册绑定手机"), MERCHANT_PROTOCOL("商户服务协议")} protocolType 协议类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {"
     * code":"1",
     * "desc":"成功",
     * "data":[
     *  {
     *    "id":1,
     *    "title":"管理列表",
     *    "lastUpdated":"2016-11-15 14:38:35",
     *    "content":"为空表示查询顶级分类列表，不为空表示该parentId下的子分类列表",
     *    "versionNo": 1,
     *    "protocolType":"CUSTOMER_PROTOCOL"
     *  }
     * ]
     * }
     */
    @RequestMapping(value = Routes.MALL_SETTLED_PROTOCOLS_INFO, method = RequestMethod.GET)
    public JsonResult protocolsInfo(HttpServletRequest request, MallProtocolDto dto) {
        RestDoing doing = jsonResult -> {
            String domain = request.getParameter("domain");
            if ("DEFAULT".equals(dto.getType())) {
                if (StringUtils.isBlank(domain)) {
                    jsonResult.remind("domain 不能为空",log);
                    return;
                }
                Mall mall = mallRepository.findByHostname(domain);
                if (mall != null) {
                    dto.setMallId(mall.getId());
                }
            }else if ("SELF".equals(dto.getType())) {
                if (StringUtils.isBlank(domain)) {
                    jsonResult.remind("domain 不能为空",log);
                    return;
                }
                Mall mall = mallRepository.findByCustomerPlatformDomain(domain);
                if (mall != null) {
                    dto.setMallId(mall.getId());
                }
            }else {

                if (dto.getMallId() == null) {
                    jsonResult.remind("平台ID 不能为空",log);
                    return;
                }
            }

            if (StringUtils.isBlank(dto.getProtocolType()) || !EnumUtils.isValidEnum(ProtocolType.class, dto.getProtocolType())) {
                jsonResult.remind("MERCHANT_PROTOCOL(\"商户服务协议\")",log);
                return;
            }
            MallProtocol mallProtocol = mallProtocolRepository.findByMallIdAndExpireAndProtocolTypeAndIsDelete(dto.getMallId(), Whether.NO, ProtocolType.valueOf(dto.getProtocolType()), Whether.NO);
            jsonResult.data = mallProtocol;
        };
        return doing.go(request, log);
    }


    /**
     * @api {post} /mall/settled_merchant 商家入驻
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {long} mallId <code>必传参数</code> 平台ID
     * @apiParam {String} realName <code>必传参数</code> 联系人
     * @apiParam {String} name <code>必传参数</code> 商户名
     * @apiParam {String} mobile <code>必传参数</code> 联系人手机
     * @apiParam {String=SELF("自定义"), DEFAULT("配置域名")} type <code>必传参数</code> 协议类型
     *
     * @apiSuccess {String=11("商户名 已经被使用"), 12("你已经加入了该平台,不用再加入")} code
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *    "code": "1",
     *    "desc": "成功",
     *    "data" : {
     *        "name" : "测试公司",
     *        "hostName" : "beta.b.uat.rockcent.com"
     *    }
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_SETTLED_MERCHANT, method = RequestMethod.POST)
    public JsonResult merchantSettled(@RequestBody MerchantDto merchantDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String domain = merchantDto.getDomain();
            if ("SELF".equals(merchantDto.getType())) {
                if (StringUtils.isBlank(domain)) {
                    jsonResult.remind("domain 不能为空",log);
                    return;
                }
                Mall mall = mallRepository.findByCustomerPlatformDomain(domain);
                if (mall != null) {
                    merchantDto.setMallId(mall.getId());
                }
            }else if ("DEFAULT".equals(merchantDto.getType())) {
                if (StringUtils.isBlank(domain)) {
                    jsonResult.remind("domain 不能为空",log);
                    return;
                }
                Mall mall = mallRepository.findByHostname(domain);
                if (mall != null) {
                    merchantDto.setMallId(mall.getId());
                }
            }else {
                if (merchantDto.getMallId() == null) {
                    jsonResult.remind("平台ID 不能为空",log);
                    return;
                }
            }
            if (merchantDto.getMallId() == null) {
                jsonResult.remind("mallId 不能为空",log);
                return;
            }
//            if (StringUtils.isBlank(merchantDto.getRealName())) {
//                jsonResult.remind("联系人 不能为空",log);
//                return;
//            }
//
//            if (StringUtils.isBlank(merchantDto.getName())) {
//                jsonResult.remind("商户名称 不能为空",log);
//                return;
//            }
//
//            if (StringUtils.isBlank(merchantDto.getMobile())) {
//                jsonResult.remind("联系方式 不能为空",log);
//                return;
//            }
//            Long merchantCount = merchantRepository.countByName(merchantDto.getName());
//            if (merchantCount.longValue() > 0L) {
//                jsonResult.custom("11", "商户名 已经被使用", log);
//                return;
//            }

            Mall mall = mallRepository.findById(merchantDto.getMallId());
            if (mall == null) {
                jsonResult.remind("所加入平台不存在",log);
                return;
            }

            Merchant merchant = merchantRepository.findByUserInfoIdAndMallId(userInfoDto.getId(), mall.getId());
            if (merchant != null) {
                jsonResult.custom("12", "你已经加入了该平台,不用再加入", log);
                return;
            }

            UserInfo userInfo = userInfoRepository.findById(userInfoDto.getId());
            if (StringUtils.isBlank(userInfo.getRealName())) {
                userInfo.setRealName(merchantDto.getRealName());
            }
            if (StringUtils.isBlank(userInfo.getEmail())) {
                userInfo.setEmail(merchantDto.getEmail());
            }
            if (StringUtils.isBlank(userInfo.getMobile())) {
                userInfo.setMobile(merchantDto.getMobile());
            }
            // 更新用户信息
            userInfoRepository.save(userInfo);
            // 创建商家信息
            merchant = mallHelper.save(userInfo, mall, merchantDto.getName());
            // 添加平台默认菜单权限
//            mallHelper.saveAuthResource(mall, userInfo.getUsername());

            //创建商家权限账号
            merchantSrv.saveUserMerchant(merchant, userInfo.getUsername());
            String hostName = mall.getHostname();
            if (StringUtils.isNotEmpty(mall.getCustomerPlatformDomain()) && mall.getOpenCustomDomain()!=null && Whether.YES.equals(mall.getOpenCustomDomain())) {
                hostName = mall.getCustomerPlatformDomain();
            }
            MallDto mallDto = new MallDto();
            mallDto.setName(mall.getName());
            mallDto.setHostName(String.format("http://%s/business/merchant/index?merchantId="+merchant.getId(), hostName));

            // 重新刷新session
            userHelper.setSession(userInfo, request);

            jsonResult.data = mallDto;
        };
        return doing.go(request, log);
    }
}
